<?php
namespace control;

// 业务凭证模板
class businessVoucherSettingClass extends adIndexClass
{
    private const page = 'businessVoucherSetting';
    private const table = 'business_voucher_template';
    private const tableMx = 'business_voucher_template_detail';
    private const tableGroupMx = 'business_voucher_subject';
    private const title = '业务凭证模板';
    private static array $ruleOption = ['汇总税额', '汇总金额', '汇总价税合计','明细税额', '明细金额', '明细价税合计'];
    private static array $subjectSourceOption = ['voucherModel'=>'凭证模板','account'=>'单据上的账户','materialSubject'=>'单据上物料的存货科目','costSubject'=>'单据上物料的销售成本科目','incomeSubject'=>'单据上物料的销售收入科目'];
    /*编码入口页*/
    public function home(): string
    {
        //费用单、收入单、费用单
        $all = $this->getPowerAll();
        //返回
        $rightHtml = $this->homeRight();
        $html =  componentClass::leftNav([
            'title'=>'类型',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html .= <<<EOT
<script>
function replaceRightDetail(obj, cla = '{$this->get('cla')}') {
     let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        let that = $(obj).parent('ul')
        const two = that.attr('pid');
        const one = that.parent('ul').attr('pid');
        // ulScal(obj, id)
        $('#container-left').find('li').removeClass('active')
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            menuOne:one,
            menuTwo: two,
            menuThree: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}
function batchDownload(formName){
    let arr = [];
    $("[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
         var vals = arr.join(",");
        location.href = root+"control/adIndex.html?cla={$this->get('cla')}&fun=batchDownLoad&listId="+vals;
    } else {
        msg('请选择需要数据');
    }
}

function batchGet(){
         cxDialog('是否确认初始化模板?', () => {
                let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
      $("#loading", window.top.document).show();
         $.post(root+"control/adIndex.html?cla={$this->get('cla')}&fun=batchGet",{},function(res) {
           if (res.warn ===2){
               location.reload()
           }else{
               msg(res.warn,'error')
           }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
         },'json')
        }, () => {
          // click no callback
        });
}
</script>
EOT;
        //返回
        return $this->homeFun($html);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "模板名称" => text(["name" => 'name']).
                        hidden(['name' => 'menuTwo', 'value' => $this->post('menuTwo')]).
                        hidden(['name' => 'menuThree', 'value' => $this->post('menuThree')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{type:'" . $this->post('menuThree') . "'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $json['html'] = $this->getPowerAll();
        return json_encode($json, 320);
    }


    /**
     * 获取业务类型
     * @return array
     */
    public function getMenuOne(): array
    {
        $result = [];
            foreach ($this->templateField() as $name=>$menu){
                if (is_array($menu) && count($menu) >0){
                    $result = array_merge($result,$menu);
                }elseif(!is_array($menu) || count($menu) ==0){
                    $result[] = $name;
                }
            }
        return $result;
    }
    /**
     * 业务凭证模板
     * @return string[][][]
     */
    public function templateField(): array
    {
        $feeTypeOption = para('reimburseType','，');
        return [
            '采购单' => [
                '采购入库',
                '采购退货',
            ],
            '销售单' => [
                '销售出库',
                '销售退货',
            ],
            '采购暂估单' => [
            ],
            '领料单' => [
            ],
            '退料单' => [
            ],
            '收款单' => [
            ],
            '付款单' => [
            ],
            '生产入库单' => [
            ],
            '其他入库单' => [
                '盘盈',
                '其他入库',
            ],
            '其他出库单' => [
                '盘亏',
                '其他出库',
            ],
            '成本调整单' => [
            ],
            '结转出库成本' => [
                '出库',
                '退货'
            ],
            '收入单' => [
            ],
            '费用单' => [
            ],
            '组装单' => [
            ],
            '拆卸单' => [
            ],
            '销项发票' => [
            ],
            '进项发票' => [
            ],

            '核销单' => [
                '预收冲应收',
                '预付冲应付',
                '应收冲应付',
                '应收转应收',
                '应付转应付',
            ],
            '转账单' => [
            ],
            '费用报销单'=>$feeTypeOption,
        ];
    }

    public function getPowerAll(array $local = [], string $pid = ''): string
    {
        $result = $local ?: $this->templateField();
        $style = empty($pid) ? 'pid=0' : ' class="child-node"';
        $temp = "<ul $style $pid>";
        // 角标
        $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
        $lastone = lastone;
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        foreach ($result as $key => $value) {
            // 判断下级是否存在
            $pid = "pid=$key";
            if (is_array($value) && !empty($value)) {
                $temp .= "<li data-id='$key' onclick=\"replaceRightDetail(this)\">$arrow <span class='textcontent'>{$textcontent_ico}{$key}</span></li>";
                $temp .= $this->getPowerAll($value, $pid);
            } else {
                if (is_array($value)) {
                    $name = $key;
                } else {
                    $name = $value;
                    $key = $value;
                }
                $temp .= "<li data-id='$key' onclick=\"replaceRightDetail(this)\">$lastone <span class='textcontent'>{$textcontent_ico}{$name}</span></li>";
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     */
    public function homeRightJson(): string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): string
    {
        return $this->homeSearch();
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => "业务类型",
                        'width' => 200,
                    ],
                    'orderNo'  => [
                        'name'  => '模板编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '模板名称',
                        'width' => 200,
                    ],
                    'defaultTemplate'          => [
                        'name'  => '默认',
                        'width' => 200,
                    ],
                    'updateStid'          => [
                        'name'  => '更新人',
                        'width' => 200,
                    ],
                    'updateTime'          => [
                        'name'  => '更新时间',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }


    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        $secMenuName = $this->post('menuThree');
        $equal = [
            'version' => '3.2',
            'coid'=>self::$coid
        ];
        //获取查询结果
        $where = search([
            "like" => [
                "name" => $this->post('name'),//单据类型
            ],
            '=' => $equal,
        ]);
        if ($secMenuName) {
            $where .= " and type = '$secMenuName'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page([
            "table" => self::table,
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'defaultTemplate':
                        $row[] = $array['defaultTemplate'] ? '是' : '否';
                        break;
                    case 'updateStid':
                        $row[] = self::findStaff($array['updateStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $this->js() . $page['button'];
        return json_encode($json, 320);
    }

    public function edit()
    {
        $id = $this->post('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $tr[] = ['借贷',  '科目来源','科目', '取值', '核算项目', '操作'];
        $all = find(array('table' => self::tableMx, 'where' => "orderId = '$id' order by list asc"));
        foreach ($all['array'] as $array) {
            $subject = query('subject',"id = '$array[subjectId]'");
            $assistAccountIds = explode(',',$subject['assistAccountIds']);
            $editIco = 'hide';
           if (in_array('现金流',$assistAccountIds) || in_array('项目',$assistAccountIds)){
               $editIco = '';
           }

            $tr[] = [
                select(array('name' => 'direction[]', 'title' => '请选择', 'option' => ['借', '贷'], 'value' => $array['direction'])),
                select(array('name' => 'subjectSource[]', 'value' => $array['subjectSource'], 'title' => '请选择', 'option' => self::$subjectSourceOption)),
                self::subjectSelect($array['subjectId']) . "<img style='cursor: pointer' onclick=\"chooseGroupSubject('$array[id]')\" src='{$this->root}img/control/setting.svg'>",
                select(array('name' => 'rule[]', 'value' => $array['rule'], 'title' => '请选择', 'option' => self::$ruleOption)),
                hidden(array('name' => 'assitItem[]', 'value' => $array['assitItem'])) . "<span class='assistName'>{$subject['assistAccountIds']}</span><img class='assistSetting $editIco' style='cursor: pointer;margin-left: 5px;vertical-align:text-top' onclick=\"chooseAssit(this)\" src='{$this->root}img/control/edit_gray.svg'>",
                "<span class='del-row-button' onclick='decline(this)'>删除</span>" . hidden(array('name' => 'mxId[]', 'value' => $array['id']))
            ];
        }
        if (is_array($all['array']) && count($all['array']) == 0) {
            $suiji = suiji();
            $tr[] = [
                select(array('name' => 'direction[]', 'title' => '请选择', 'value' => '借', 'option' => ['借', '贷'])),
                select(array('name' => 'subjectSource[]', 'value' => 'voucherModel', 'title' => '请选择', 'option' => self::$subjectSourceOption)),
                self::subjectSelect() . "<img style='cursor: pointer' onclick=\"chooseGroupSubject('$suiji')\" src='{$this->root}img/control/setting.svg'>",
                select(array('name' => 'rule[]', 'title' => '请选择', 'option' => self::$ruleOption)),
                hidden(array('name' => 'assitItem[]')) . "<span class='assistName'></span><img class='assistSetting hide' style='cursor: pointer;margin-left: 5px;vertical-align:text-top' onclick=\"chooseAssit(this)\" src='{$this->root}img/control/edit_gray.svg'>",
                "<span class='del-row-button' onclick='decline(this)'>删除</span>" . hidden(array('name' => 'mxId[]', 'value' => $suiji))
            ];
        }
        $summaryArr = $info['summary'] ? json_decode($info['summary'], true) : [];
        $summaryArr['preSummary'] = $info['preSummary'];
        $summaryArr['suffixSummary'] = $info['suffixSummary'];
        $summary = json_encode($summaryArr, 320);
        $summaryName = $this->composeSummaryName($summaryArr);
        $voucher_word_default = query('voucher_word',"isDefault = '是' and coid = '".self::$coid."'");
        $html = $this->layerEdit(array("table" => array(
            /*array(
                "<div style='padding: 0 10px;display: flex;flex-direction: row;justify-content: space-between'><div>业务类型：" . select(array('name' => 'type', 'title' => '请选择', 'option' => $this->getMenuOne(), 'value' => $info['type']?:$this->post('type'))) . "</div><div>模板名称：" . text(array('name' => 'name', 'value' => $info['name'])) . "</div><div>凭证字：" . idSelect(array('name' => 'wordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "' order by time asc", 'title' => '请选择', 'sqlId' => "id", 'sqlField' => 'word', 'value' => $info['wordId']?:$voucher_word_default['id'])) . "</div>" . self::singleCheckBox('defaultTemplate', 1, '默认', $info['defaultTemplate']) . "</div>"
            ),*/
            array(
                "业务类型" => select(array('name' => 'type', 'title' => '请选择', 'option' => $this->getMenuOne(), 'value' => $info['type']?:$this->post('type'))),
                "模板名称" => text(array('name' => 'name', 'value' => $info['name'])),
            ),
            array(
                "凭证字" => idSelect(array('name' => 'wordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "' order by time asc", 'title' => '请选择', 'sqlId' => "id", 'sqlField' => 'word', 'value' => $info['wordId']?:$voucher_word_default['id'])),
                "默认" => self::singleCheckBox('defaultTemplate', 1, '', $info['defaultTemplate']),
            ),
            array(
                "<div style='padding: 0 10px'><div>摘要：<span id='summaryText'>$summaryName</span><img style='margin-left: 5px' onclick=\"chooseSummary(this)\" src=\"{$this->root}img/control/edit.svg\"  class=\"listIco\"></div><input name='summary' type='hidden' value='$summary'></div>"
            ),
            array(
                "<div id='templateTable'>" . $this->tableMany(array('tr' => $tr, 'end' => true, 'button' => true, 'method' => "addRow(this)")) . "</div>"
            ),
        )));
        $html .= "<style>.layerList .subjectSelector{width: 90% !important;}</style>";
        return $this->layer(array("title" => "编辑" . self::title, "height" => 600, "width" => 1000, "html" => $html));
    }


    public function groupSubject(): bool|string
    {
        $type = $this->post('type');//业务类型
        $allowType = array_merge(para('reimburseType','，'),['收入单','费用单']);
        if (empty($type)){
            $html = '请先选择业务类型';
        }elseif(!in_array($type,$allowType)){
            $html = '仅费用报销单、收入单、费用单可用';
        }else{
            $cla = self::page;
            $mxId = $this->post('mxId');
            $tr[] = ['类型', '科目', '操作'];
            $all = find(array('table' => 'business_voucher_subject', 'where' => "orderId = '$mxId' and coid = '" . self::$coid . "' order by list asc"));
            $obj = new otherInReceiptClass();
            $feeTypeOption = match ($type){
                '收入单'=>$obj->inOutType('收'),
                '费用单'=>$obj->inOutType('支'),
                default=>para('costType', '，')
            };
            foreach ($all['array'] as $array) {
                $tr[] = [
                    select(array('name' => 'feeType[]', 'option' => $feeTypeOption, 'title' => '请选择', 'value' => $array['type'])),
                    self::subjectSelect($array['subjectId']),
                    "<span class='del-row-button' onclick='decline(this)'>删除</span>" . hidden(array('name' => 'groupSubjectId[]', 'value' => $array['id']))
                ];
            }
            $table = $this->tableMany(['tr' => $tr, 'end' => true, 'button' => true, 'method' => "addGroupRow(this)"]);
            $html = <<<eof
<form name="groupForm">
<div style='padding: 10px'>
    <div id="groupTable" class="layerList">$table</div>
    <input name="sourceId" value="$mxId" type="hidden">
    <input name="allowType" value="$type" type="hidden">
</div>
</form>
eof;
            $button = "<input type='button' onclick=\"commitForm('groupForm',root+'control/adIndex.html?cla=$cla&fun=saveGroupSubject')\" class='button  confirm' value='保存'>";
        }
        return $this->layer(array("title" => "科目设置", "height" => 700,'zindex'=>10, "width" => 1000, "html" => $html, "button" => $button??' '));
    }

    public function saveGroupSubject(): bool|string
    {
        $sourceId = $this->post('sourceId');
        $mxIdArr = $this->post('groupSubjectId') ?: [];
        $feeTypeArr = $this->post('feeType');
        $subjectIdArr = $this->post('subjectId');
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请添加类型和对应的科目';
        } elseif (static::is_null_array($feeTypeArr)) {
            $json['warn'] = "请选择类型";
        } elseif (static::is_null_array($subjectIdArr)) {
            $json['warn'] = "请选择科目";
        } elseif (empty($sourceId)) {
            $json['warn'] = "未找到ID";
        } else {
            $this->startTrans();//开启事务
            $json['warn'] = '新增成功';
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableGroupMx, "id = '$nid'");
                $subject = query('subject', "id = '$subjectIdArr[$k]'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableGroupMx,
                        "field" => [
                            'type' => $feeTypeArr[$k],
                            'subjectId' => $subjectIdArr[$k],
                            'subjectCode' => $subject['code'],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableGroupMx,
                        "field" => [
                            'id' => $nid,
                            'coid' => self::$coid,
                            'orderId' => $sourceId,
                            'type' => $feeTypeArr[$k],
                            'subjectId' => $subjectIdArr[$k],
                            'subjectCode' => $subject['code'],
                            'draft' => 1
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //删除不在此ID中的数据
                delete(array('table' => self::tableGroupMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$sourceId'"));
                //添加日志
                $text = $this->control['name'] . "编辑了类型和科目对照表， 来源ID：【" . $sourceId . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
                $json['hiddenPanel'] = 'businessVoucherSettingGroupSubject';//需要隐藏的弹窗的ID
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 复选框
     * @param $name
     * @param $value
     * @param $text
     * @param $checked
     * @return string
     *
     */
    public static function singleCheckBox($name, $value, $text, $checked): string
    {
        $selected = '';
        if ($checked == $value) {
            $selected = 'checked';
        }
        return <<<eof
<label class="checkbox"><input name='$name' type='checkbox' $selected value='$value' ><span></span>&nbsp;$text</label>
eof;

    }

    public function js()
    {
        $cla = self::page;
        return <<<eof
<script>
function chooseSummary(){
     let summary = $("[name='summary']").val();
     layer('$cla','summaryEdit',{summary:summary})
}

function chooseAssit(e){
    let selectorId = $(e).parent().parent().find("[name='subjectName[]']").attr('id');
    let assit = $("#"+selectorId).parent().parent().parent().find("[name='assitItem[]']").val();
    layer('$cla','cashFlow',{assitItem:assit,selectorId:selectorId})
}
function addGroupRow(e){
    let type = $("form[name='groupForm'] [name='allowType']").val();
     $.post(root+'control/adIndex.html?cla=$cla&fun=addGroupRow',{type:type},function (res){
         $(e).parent().before(res.html);
     },'json');
}
function addRow(e) {
   $.post(root+'control/adIndex.html?cla=$cla&fun=addRow',{},function(res) {
    $(e).parent().before(res.html);
   },'json')
}
       
function chooseSubject(e,isShow){
    let rowId = $(e).parent().find("[name='subjectName[]']").attr('id');
    layer('component','subject',{isShow:isShow,rowId:rowId})
}
function chooseSubjectId(e){
    let id = $(e).data('id');
    let name = $(e).data('name');
    $(e).parent().find("li").css('background-color','white');
    $(e).css('background-color',"rgb(242, 242, 242)");
    $("[name='chooseId']").val(id);
    $("[name='chooseName']").val(name);
}
function confirmBtn(selectorId){
    let id =  $("[name='chooseId']").val();
    let name =  $("[name='chooseName']").val();
    if (!id){
        msg('请选择科目','error')
        return false;
    }
    $("#"+selectorId).siblings("input[name='subjectId[]']").val(id);
    $("#"+selectorId).val(name);
    
    requestAssit(id,selectorId);
    $('#componentSubject').hide()
}
function chooseGroupSubject(id){
    let type =$("[name='type']").val();
    layer('$cla','groupSubject',{mxId:id,type:type})
}
/**
* 辅助核算
*/
function requestAssit(subjectId,selectorId){
    $.post(root+'control/adIndex.html?cla=$cla&fun=getAssitName',{subjectId:subjectId},function(res) {
      if (res.warn ===2){
          $("#"+selectorId).parent().parent().parent().find(".assistName").html(res.assistAccountIds);
          if (res.html==='show'){
              $("#"+selectorId).parent().parent().parent().find(".assistSetting").show();
          }else{
               $("#"+selectorId).parent().parent().parent().find(".assistSetting").hide();
          }
      }else{
          msg(res.warn,'error');
      }
    },'json')
}

/**
* 保存现金流
*/
function saveCash(form,selectorId){
    let cashCode = $("[name='"+form+"'] [name='cashCode']").val();
    let projectCode = $("[name='"+form+"'] [name='projectCode']").val();
    let json = {
        cashCode:cashCode,
        projectCode:projectCode
    };
    $("#"+selectorId).parent().parent().parent().find("[name='assitItem[]']").val(JSON.stringify(json));
    $('#businessVoucherSettingCashFlow').hide();
}

/**
* 保存摘要
*/
function saveSummary(){
     $.post(root+'control/adIndex.html?cla=$cla&fun=saveSummary',$("[name='businessVoucherSettingSummaryEditForm']").serialize(),function(res) {
       $("[name='summary']").val(JSON.stringify(res.summaryVal));
       $("#summaryText").html(res.html);
       $('#businessVoucherSettingSummaryEdit').hide()
    },'json')
}
function commitForm(form, url) {

    //防止高频点击
    var date = new Date();
    var time = date.getTime(); //毫秒时间戳
    let finger = 2;
    if (typeof minTime == "undefined") {
        minTime = time + 2000; //下次点击的最小时间
    } else {
        if (minTime && time < minTime) {
            finger = 1;
            warn("操作过于频繁");
            console.log("time:" + time + "，mintime:" + minTime + "，差额：" + (time - minTime));
        } else {
            finger = 2;
            minTime = time + 2000; //下次点击的最小时间
        }
    }

    if (finger === 2) {
        let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
        //异步提交数据
        $.post(url, serialize, function (data) {
            //console.log(data);
            if (data.warn === 2) {
               if (data.hiddenPanel){
                   $("#"+data.hiddenPanel).hide();
               }
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
    }
}
</script>
<style>
.subjectSelector{padding-right: 34px !important;width: 177px !important;}
.pageMenu{margin: 10px 0 0;}
.pageMenu > ul {
    padding: 0 20px;
}
.pageMenu > ul > li {
    float: left;
    padding: 6px 10px;
    background-color: rgb(255, 255, 255);
    cursor: pointer;
}
.subject-ul>li{padding: 2px 10px;cursor: pointer}
.subject-ul>li:hover{background-color: rgb(242, 242, 242)}
.subject-div{   
    height: 450px;
    margin: 5px 0 5px 0;
    border-radius: 2px;
    overflow: auto;
    }
.confirm{
  width: 100px;
}
    .cancel,.cancel:hover{
        width: 100px;
        background-color: white;
        color: #7F7F7F;
        border: 1px solid rgba(215, 215, 215, 1);
        margin-right: 5px;
    }
</style>
eof;

    }

    private function getFieldName($field): string
    {
        return match ($field) {
            'orderNo' => '单据编号',
            'department' => '部门',
            'staff' => '员工',
            default => '',
        };
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $summary = $this->post('summary') ? json_decode(htmlspecialchars_decode($this->post('summary')), true) : [];
        $mxIdArr = $this->post('mxId');
        $directionArr = $this->post('direction');
        $subjectIdArr = $this->post('subjectId');
        $ruleArr = $this->post('rule');
        $assitItemArr = $this->post('assitItem');
        $subjectSourceArr = $this->post('subjectSource');
        $summaryRes = $summary;
        unset($summaryRes['preSummary']);
        unset($summaryRes['suffixSummary']);
        $field = [
            'type' => $this->post('type'),
            'name' => $this->post('name'),
            'preSummary' => $summary['preSummary'] ?? '',
            'summary' => json_encode($summaryRes,320),
            'suffixSummary' => $summary['suffixSummary'] ?? '',
            'wordId' => $this->post('wordId'),
            'defaultTemplate' => $this->post('defaultTemplate'),
        ];
        $annotation = [
            'type' => '业务类型',
            'name' => '模板名称',
            'wordId' => '凭证字',
        ];
        $rules = [
            'type' => 'required',
            'name' => 'required',
            'wordId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($summary)) {
            $json['warn'] = '请设置摘要';
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择科目';
        } elseif (static::is_null_array($subjectIdArr) && static::is_null_array($subjectSourceArr)) {
            $json['warn'] = '请选择科目或选择科目来源';
        } elseif (static::is_null_array($directionArr)) {
            $json['warn'] = '请选择借贷方向';
        } elseif (static::is_null_array($ruleArr)) {
            $json['warn'] = '请选择取值';
        } elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and name = '$field[name]' and id != '$id'")) >0){
            $json['warn'] = '已存在此模板名称';
        }else {
            if (static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and type = '$field[type]' and defaultTemplate = 1")) ==0){
                $field['defaultTemplate'] = 1;
            }
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            $last = query(self::table, "coid = '" . self::$coid . "' order by orderNo desc");
            $userNo = sprintf("%03d", (int)$last['orderNo'] + 1);
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'version' => '3.2',
                    'coid' => self::$coid,
                    'updateStid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            foreach ($mxIdArr as $k => $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                if (empty($mx['id'])) {
                    $warn = insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => $mxId,
                            'coid' => self::$coid,
                            'orderId' => $id,
                            'subjectId' => $subjectIdArr[$k],
                            'subjectSource'=>$subjectSourceArr[$k],
                            'direction' => $directionArr[$k],
                            'rule' => $ruleArr[$k],
                            'assitItem' => htmlspecialchars_decode($assitItemArr[$k]),
                        ]
                    ));
                } else {
                    $warn = update(array(
                        'table' => self::tableMx,
                        'field' => [
                            'subjectId' => $subjectIdArr[$k],
                            'direction' => $directionArr[$k],
                            'subjectSource'=>$subjectSourceArr[$k],
                            'rule' => $ruleArr[$k],
                            'assitItem' => htmlspecialchars_decode($assitItemArr[$k]),
                        ],
                        'where' => "id = '$mxId'"
                    ));
                }
                //更新费用类型和科目对照表
                $bool = update(array(
                   'table'=>self::tableGroupMx,
                   'field'=>[
                       'draft'=>0
                   ],
                    'where'=>"coid = '".self::$coid."' and orderId = '$mxId'"
                ));
                if ($field['defaultTemplate']){
                    update(array(
                        'table'=>self::table,
                        'field'=>[
                            'defaultTemplate'=>0
                        ],
                        'where'=>"coid = '".self::$coid."' and type = '$field[type]' and id !='$id'"
                    ));
                }
                if (!in_array($warn, ['新增成功', '更新成功']) || $bool !='更新成功') {
                    $json['warn'] = '编辑模板明细失败';
                    break;
                }
            }


            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table'=>self::tableMx,'where'=>"coid = '".self::$coid."' and orderId = '$id' and id not in ('".implode("','",$mxIdArr)."')"));


                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 组装摘要数据
     * @return bool|string
     */
    public function saveSummary(): bool|string
    {
        $field = [
            'preSummary' => $this->post('preSummary'),
            'suffixSummary' => $this->post('suffixSummary'),
            'orderNo' => $this->post('orderNo') ?: '',
            'department' => $this->post('department') ?: '',
            'staff' => $this->post('staff') ?: '',
        ];
        $json['html'] = $this->composeSummaryName($field);
        $json['summaryVal'] = $field;
        return json_encode($json, 320);
    }


    /**
     * 组成摘要名称
     * @param $field
     * @return string
     */
    private function composeSummaryName($field): string
    {
        $field['preSummary'] = $field['preSummary']??'';
        $field['orderNo'] = $field['orderNo']??'';
        $field['department'] = $field['department']??'';
        $field['staff'] = $field['staff']??'';
        $field['suffixSummary'] = $field['suffixSummary']??'';
        $summary = $field['preSummary'] ? ('_' . $field['preSummary']) : '';
        $summary .= $this->getFieldName($field['orderNo']) ? ('_' . $this->getFieldName($field['orderNo'])) : '';
        $summary .= $this->getFieldName($field['department']) ? ('_' . $this->getFieldName($field['department'])) : '';
        $summary .= $this->getFieldName($field['staff']) ? ('_' . $this->getFieldName($field['staff'])) : '';
        $summary .= $field['suffixSummary'] ? ('_' . $field['suffixSummary']) : '';
        return ltrim($summary, '_');
    }

    private function assistRelation()
    {
        return [
            '采购单' => [
                'assist' => [
                    '客户' => '',
                    '供应商' => 'supplierId',
                    '员工' => 'stid',
                    '部门' => '',
                    '项目' => '',
                    '存货' => 'materialId',
                    '现金流' => '',
                ],
                'table' => 'purchase_order',
                'tableMx' => 'purchase_order_detail'
            ]
        ];
    }

    public function summaryEdit()
    {
        $summary = $this->post('summary');
        $summaryArr = json_decode(htmlspecialchars_decode($summary), true);
        $tr[] = ['摘要前缀', '单据编号', '部门', '员工', '摘要后缀'];
        $tr[] = [
            text(array('name' => 'preSummary', 'value' => $summaryArr['preSummary'] ?? '')),
            self::singleCheckBox('orderNo', 'orderNo', '', $summaryArr['orderNo'] ?? ''),
            self::singleCheckBox('department', 'department', '', $summaryArr['department'] ?? ''),
            self::singleCheckBox('staff', 'staff', '', $summaryArr['staff'] ?? ''),
            text(array('name' => 'suffixSummary', 'value' => $summaryArr['suffixSummary'] ?? '')),
        ];
        $html = $this->layerEdit(array("table" => array(
            array(
                $this->listTable(['tr' => $tr, 'end' => true])
            ),
        )
        ));
        return $this->layer(array(
            'zindex'=>10,
            "title" => "编辑" . self::title,
            "height" => 600,
            "width" => 1000,
            "html" => "<div>".$html."</div>",
            'button' => "<input onclick=\"saveSummary()\" type='button' class='button' value='保存'>"
        ));
    }

    /**
     * 选中现金流
     * @return false|string
     */
    public function cashFlow(): bool|string
    {
        $assitItem = $this->post('assitItem');
        $assitResult = $this->post('assitItem')?json_decode(htmlspecialchars_decode($assitItem), true):[];
        $selectorId = $this->post('selectorId');
        $html = $this->layerEdit(array("table" => array(
            array(
                '现金流：' => idSelect(array('name' => 'cashCode', 'class' => 'width300', 'sqlForm' => "cash where coid = '" . self::$coid . "' order by code", 'title' => '请选择', 'sqlId' => 'code', 'value' => $assitResult['cashCode'] ?? '', 'sqlField' => 'name'))
            ),
            array(
                '项目：' => idSelect(array('name' => 'projectCode', 'class' => 'width300', 'sqlForm' => "project where coid = '" . self::$coid . "' order by orderNo", 'title' => '请选择', 'sqlId' => 'orderNo', 'value' => $assitResult['projectCode'] ?? '', 'sqlField' => 'name'))
            ),
        )
        ));
        return $this->layer(array(
            "title" => "编辑" . self::title,
            "height" => 600,
            "width" => 1000,
            "html" => $html,
            'button' => "<input onclick=\"saveCash('businessVoucherSettingCashFlowForm','{$selectorId}')\" type='button' class='button' value='保存'>"
        ));
    }

    /**
     * 获取辅助项目核算
     */
    public function getAssitName()
    {
        $subjectId = $this->post('subjectId');
        $subject = query('subject', "id = '$subjectId'");
        if (empty($subject['id'])) {
            $json['warn'] = '未找到科目';
        } else {
            $json['warn'] = 2;
            $assistAccountIds = explode(',', $subject['assistAccountIds']);
            if (in_array('现金流', $assistAccountIds) || in_array('项目', $assistAccountIds)) {
                $json['html'] = 'show';
            } else {
                $json['html'] = 'hidden';
            }
            $json['assistAccountIds'] = $subject['assistAccountIds'];
        }
        return json_encode($json, 320);
    }

    /**
     * 类型科目对照追加一行
     * @return false|string
     */
    public function addGroupRow(): bool|string
    {
        $obj = new otherInReceiptClass();
        $feeTypeOption = match ($this->post('type')){
            '收入单'=>$obj->inOutType('收'),
            '费用单'=>$obj->inOutType('支'),
            default=>para('costType', '，')
        };
        $tr[] = [
            select(array('name' => 'feeType[]', 'option' => $feeTypeOption, 'title' => '请选择')),
            self::subjectSelect(),
            "<span class='del-row-button' onclick='decline(this)'>删除</span>" . hidden(array('name' => 'groupSubjectId[]', 'value' => suiji()))
        ];
        $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * 增加一行
     * @return false|string
     */
    public function addRow()
    {
        $suiji = suiji();
        $tr[] = [
            select(array('name' => 'direction[]', 'title' => '请选择', 'value' => '借', 'option' => ['借', '贷'])),
            select(array('name' => 'subjectSource[]', 'value' => 'voucherModel', 'title' => '请选择', 'option' => self::$subjectSourceOption)),
            self::subjectSelect() . "<img style='cursor: pointer' onclick=\"chooseGroupSubject('$suiji')\" src='{$this->root}img/control/setting.svg'>",
            select(array('name' => 'rule[]', 'title' => '请选择', 'option' => self::$ruleOption)),
            hidden(array('name' => 'assitItem[]')) . "<span class='assistName'></span><img class='assistSetting hide' style='cursor: pointer;margin-left: 5px;vertical-align:text-top' onclick=\"chooseAssit(this)\" src='{$this->root}img/control/edit_gray.svg'>",
            "<span class='del-row-button' onclick='decline(this)'>删除</span>" . hidden(array('name' => 'mxId[]', 'value' => $suiji))
        ];
        $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     * 科目选择器
     */
    public static function subjectSelect($subjectId = '', $isShowParent = true): string
    {
        $subject = query('subject', "id = '$subjectId'");
        $selectorId = suiji();
        $html = "<span style='position: relative'>" . text(array('name' => 'subjectName[]', 'data'=>['name'=>'subjectId[]'],'class' => 'subjectSelector', 'id' => $selectorId, 'title' => '科目', 'value' => $subject['code'] .' '. $subject['name'])) . hidden(array('name' => 'subjectId[]', 'value' => $subject['id'])) . "<img onclick='chooseSubject(this,\"{$isShowParent}\")' style='position:absolute;right:10px;top:1px;cursor: pointer;' src='" . root . "img/control/find.svg?v=2'/></span>";
        $html .= <<<eof
<script>
$("#{$selectorId}").bigAutocomplete({
    width:200,
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id);
       e.parent().parent().parent().find(".assistName").html('')
       requestAssit(data.id,e.attr('id'));
}}) 
</script>
eof;
        return $html;
    }

    /**
     * 生成初始模板
     */
    public function batchGet()
    {
        $yumuSecretKey = para('yumuSecretKey');
        $yumuSecretId = para('yumuSecretId');
        $yumuApiHost = para('yumuApiHost');
        $params = [
            'version' => '3.1',
            'timestamp' => time(),
            'secretId' => $yumuSecretId,
        ];
        ksort($params); //按照key升序排列
        $strTemp = '';
        foreach ($params as $key => $item) {
            $strTemp .= $key . '=' . $item . '&'; //整合新的参数数组
        }
        $signTemp = $strTemp . "secretKey=" . $yumuSecretKey; //拼接secret
        $signature = md5($signTemp);

        $result = self::curlGet($yumuApiHost . "/interface/v1/index?cla=holidayApp&fun=importTemplate&" . $strTemp . "&signature=" . $signature, [], 60);
        $res = json_decode($result, true);
        if ($res['code'] == 1) {
            $text = '';
            $this->startTrans();
            delete(array('table' => self::table, 'where' => "1=1"));
            foreach ($res['data']['list'] as $array) {
                $warn = static::insert(array(
                    'table' => self::table,
                    'field' => [
                        'id' => suiji(),
                        'version' => '3.2',
                        'typeOne' => $array['typeOne'],
                        'type' => $array['type'],
                        'name' => $array['name'],
                        'fileName' => $array['fileName'],
                        'src' => $array['src'],
                        'format' => $array['format'],
                        'size' => $array['size'],
                        'updateStid' => self::$stid,
                    ]
                ));
                if ($warn != '新增成功') {
                    $text = '新增默认业务凭证模板失败';
                    break;
                } else {
                    $url = substr($array['src'], 0, strrpos($array['src'], '/'));
                    $this->_mkdir($url);
                    $src = serverRoot . $array['src']; //保存附件的根目录路径
                    $this->saveHttpFile($array['fullSrc'], $src);
                }
            }
            if ($text) {
                $this->rollback();
                $json['warn'] = $text;
                $this->logText(array("type" => self::page, "text" => $this->control['name'] . '获取默认业务凭证模板失败：' . $text));
            } else {
                $this->commitTrans();
                $json['warn'] = 2;
                $_SESSION['warn'] = '初始化成功';
                $this->logText(array("type" => self::page, "text" => $this->control['name'] . '获取默认业务凭证模板成功'));
            }

        } else {
            $json['warn'] = "请求接口失败：" . $res['warn'];
            $this->logText(array("type" => self::page, "text" => "请求接口失败：" . $res['warn']));
        }
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                delete(array('table' => self::tableGroupMx, 'where' => "orderId in (select id from ".self::tableMx." where orderId ='$id')"));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));

                    //返回
                    $warn = "删除成功";
                    $x++;
                $text .= self::title . "ID【" . $info['id'] . "】，模板名称【" . $info['name'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
